package org.codeart.memento.example02;

import lombok.Data;

import java.util.ArrayList;
import java.util.Random;

/**
 * 玩家类
 */
@Data
public class Player {

    // 金币
    private int money;
    
    public static final String TASTY = "tasty";

    // 玩家获得的水果
    private ArrayList<String> fruits = new ArrayList<>();

    private static final String[] fruitsNames = {"Apple", "Grape", "Banana", "Orange"};

    private final Random random = new Random();

    public Player(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public String getFruit() {
        String prefix = "";
        if (random.nextBoolean()) {
            prefix = TASTY;
        }

        // 从数组中拿一个水果
        String fruit = fruitsNames[random.nextInt(fruitsNames.length)];
        return prefix + fruit;
    }
    
    // 掷色子
    public void play() {
        int dice = random.nextInt(6) + 1;
        if (dice == 1) {
            money += 100;
            System.out.println("所持有的金币增加了...");
        } else if (dice == 2) {
            money /= 2;
            System.out.println("所持有的金币减少了...");
        } else if (dice == 6) {
            String fruit = getFruit();
            System.out.println("获取了水果: " + fruit);
            fruits.add(fruit);
        } else {
            System.out.println("无效数据, 继续投掷!");
        }
    }
    
    // 拍摄快照
    public Memento createMemento() {
        Memento memento = new Memento(money);
        for (String fruit : fruits) {
            // 只保存好吃的水果
            if (fruit.startsWith(TASTY)) {
                memento.addFruit(fruit);
            }
        }
        return memento;
    }
    
    // 撤销
    public void restore(Memento memento) {
        this.money = memento.getMoney();
        this.fruits = memento.getFruits();
    }
}
